import type { Plugin } from 'vite';

interface PerformancePluginOptions {
  enabled?: boolean;
  threshold?: number;
  logger?: boolean;
}

export function performanceMonitor(options: PerformancePluginOptions = {}): Plugin {
  const {
    enabled = process.env.NODE_ENV === 'development',
    threshold = 100, // ms
    logger = true,
  } = options;

  return {
    name: 'performance-monitor',

    configureServer(server) {
      if (!enabled) return;

      const performanceData = new Map<string, number[]>();

      server.middlewares.use((req, res, next) => {
        const start = performance.now();

        res.on('finish', () => {
          const duration = performance.now() - start;
          const url = req.url || 'unknown';

          if (!performanceData.has(url)) {
            performanceData.set(url, []);
          }

          performanceData.get(url)!.push(duration);

          if (duration > threshold && logger) {
            console.warn(`[Performance] Slow request: ${url} (${duration.toFixed(2)}ms)`);
          }
        });

        next();
      });

      // 提供性能数据端点
      server.middlewares.use('/__performance', (req, res) => {
        const stats: Record<string, any> = {};

        performanceData.forEach((values, url) => {
          if (values.length > 0) {
            stats[url] = {
              count: values.length,
              average: values.reduce((a, b) => a + b, 0) / values.length,
              min: Math.min(...values),
              max: Math.max(...values),
            };
          }
        });

        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify(stats, null, 2));
      });
    },
  };
}

interface DevToolsPluginOptions {
  enabled?: boolean;
  port?: number;
  logger?: boolean;
}

export function devToolsIntegration(options: DevToolsPluginOptions = {}): Plugin {
  const {
    enabled = process.env.NODE_ENV === 'development',
    port = 9229,
    logger = true,
  } = options;

  return {
    name: 'dev-tools-integration',

    configureServer(server) {
      if (!enabled) return;

      // 开发工具状态
      const devToolsState = {
        enabled: true,
        breakpoints: new Set<string>(),
        watchers: new Set<string>(),
        consoleOverrides: new Map<string, Function>(),
      };

      // WebSocket 命令处理
      server.ws.on('dev-tools-command', (data) => {
        const { command, payload } = data;

        if (logger) {
          console.log('[DevTools] Command received:', command);
        }

        switch (command) {
          case 'toggle-breakpoint':
            const { file, line } = payload;
            const breakpointKey = `${file}:${line}`;

            if (devToolsState.breakpoints.has(breakpointKey)) {
              devToolsState.breakpoints.delete(breakpointKey);
            } else {
              devToolsState.breakpoints.add(breakpointKey);
            }

            server.ws.send({
              type: 'custom',
              event: 'breakpoint-toggled',
              data: { file, line, active: devToolsState.breakpoints.has(breakpointKey) },
            });
            break;

          case 'add-watcher':
            devToolsState.watchers.add(payload.expression);
            server.ws.send({
              type: 'custom',
              event: 'watcher-added',
              data: { expression: payload.expression },
            });
            break;

          case 'remove-watcher':
            devToolsState.watchers.delete(payload.expression);
            server.ws.send({
              type: 'custom',
              event: 'watcher-removed',
              data: { expression: payload.expression },
            });
            break;

          case 'console-override':
            devToolsState.consoleOverrides.set(payload.method, payload.handler);
            break;
        }
      });

      // 提供开发工具状态
      server.middlewares.use('/__dev-tools-state', (req, res) => {
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify({
          breakpoints: Array.from(devToolsState.breakpoints),
          watchers: Array.from(devToolsState.watchers),
          enabled: devToolsState.enabled,
        }, null, 2));
      });
    },
  };
}

// 插件组合
export function createDevPlugins(options: {
  performance?: boolean;
  devTools?: boolean;
} = {}) {
  const plugins: Plugin[] = [];

  if (options.performance !== false) {
    plugins.push(performanceMonitor());
  }

  if (options.devTools !== false) {
    plugins.push(devToolsIntegration());
  }

  return plugins;
}